<template>
  <div class="content">
    <el-table highlight-current-row :data="dataList" @row-click="handleClick">
      <el-table-column prop="songName" label="歌曲" />
      <el-table-column prop="singerName" label="歌手" />
      <el-table-column prop="introduction" label="专辑" />
      <el-table-column label="编辑" width="80" align="center">
        <template #default="scope">
          <el-dropdown>
            <el-icon @click="handleEdit(scope.row)"><MoreFilled /></el-icon>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item
                  :icon="Download"
                  @click="
                    downloadMusic({
                      songUrl: scope.row.url,
                      songName: scope.row.name,
                    })
                  "
                  >下载</el-dropdown-item
                >
                <el-dropdown-item
                  :icon="Delete"
                  v-if="show"
                  @click="deleteCollection({ id: scope.row.id })"
                  >删除</el-dropdown-item
                >
                <el-dropdown-item
                  :icon="Wallet"
                  @click="paySong({ songId: scope.row.id, userId: userId })"
                  >支付</el-dropdown-item
                >
                <el-dropdown-item
                  :icon="ShoppingCart"
                  v-if="token"
                  @click="
                    addCart({
                      songId: scope.row.id,
                      userId: userId,
                      price: scope.row.price,
                    })
                  "
                  >添加到购物车</el-dropdown-item
                >
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script lang="ts">
import {
  defineComponent,
  getCurrentInstance,
  toRefs,
  computed,
  reactive,
} from "vue";
import {
  MoreFilled,
  Delete,
  Download,
  Wallet,
  ShoppingCart,
} from "@element-plus/icons-vue";

import mixin from "@/mixins/mixin";
import { HttpManager } from "@/api";
import { Icon } from "@/enums";
import { useConfigureStore, useUserStore } from "@/store";

export default defineComponent({
  components: {
    MoreFilled,
  },
  props: {
    songList: Array,
    show: {
      default: false,
    },
  },
  emits: ["changeData"],
  setup(props) {
    const {
      getSongTitle,
      getSingerName,
      playMusic,
      checkStatus,
      downloadMusic,
    } = mixin();
    const { proxy } = getCurrentInstance();
    const store = useConfigureStore();
    const userStore = useUserStore();
    const { songList } = toRefs(props);

    const iconList = reactive({
      dislike: Icon.Dislike,
      like: Icon.Like,
    });

    const songUrl = computed(() => useSongStore.songUrl);
    const singerName = computed(() => useSongStore.singerName);
    const songTitle = computed(() => useSongStore.songTitle);
    const token = computed(() => useConfigureStore.token);

    const dataList = computed(() => {
      const list = [];
      songList.value.forEach((item: any, index) => {
        item["songName"] = getSongTitle(item.name);
        item["singerName"] = getSingerName(item.name);
        item["index"] = index;
        list.push(item);
      });
      return list;
    });
    async function downloadMusicTwo(id) {
      // try {
      //   const result = (await HttpManager.downloadMusicTwo(id)) as ResponseBody;
      //   if (result.success) {
      //     (proxy as any).$message({
      //       message: result.message,
      //       type: result.type,
      //     });
      //   }
      // } catch (err) {
      //   (proxy as any).$message({
      //     message: err,
      //     type: 'error',
      //   });
      // }
    }
    // 单击歌曲列表的行，把对应的歌曲信息，存入Store 全局状态管理器中
    function handleClick(row) {
      playMusic({
        id: row.id,
        url: row.url,
        pic: row.pic,
        index: row.index,
        name: row.name,
        lyric: row.lyric,
        currentSongList: songList.value,
      });
    }

    function handleEdit(row) {
      console.log("row", row);
    }

    const userId = computed(() => userStore.userId);

    async function deleteCollection({ id }) {
      if (!checkStatus()) return;
      const result = (await HttpManager.deleteCollection(
        userStore.userId,
        id
      )) as ResponseBody;
      (proxy as any).$message({
        message: result.message,
        type: result.type,
      });
      proxy.$emit("changeData", result.data);
    }
    //歌曲支付
    async function paySong({ songId, userId }) {
      if (!checkStatus()) return;
      const result1 = (await HttpManager.getPaystatus(
        songId,
        userId
      )) as ResponseBody;
      // 判断是否支付过
      if (result1.data) {
        (proxy as any).$message({
          message: "歌曲已经支付",
          type: result1.type,
        });
        return;
      }
      //打开支付宝付款页面
      let songIds = [];
      songIds.push(songId);
      // 获取支付链接
      const result2 = (await HttpManager.toPay(
        songIds,
        userId,
        1
      )) as ResponseBody;
      if (result2.success) {
        const divForm = document.getElementsByTagName("div");
        if (divForm.length) {
          document.body.removeChild(divForm[0]);
        }
        const div = document.createElement("div");
        div.innerHTML = result2.data;
        document.body.appendChild(div);

        document.forms[0].setAttribute("target", "_self"); //_blank新开窗口跳转
        document.forms[0].submit();
      } else {
        (proxy as any).$message({
          message: result2.message,
          type: result2.type,
        });
      }
    }

    async function addCart({ songId, userId, price }) {
      const result = (await HttpManager.addCart(
        songId,
        userId,
        price
      )) as ResponseBody;
      (proxy as any).$message({
        message: result.message,
        type: result.type,
      });
    }
    return {
      dataList,
      iconList,
      Delete,
      Download,
      songUrl,
      singerName,
      songTitle,
      handleClick,
      handleEdit,
      downloadMusic,
      deleteCollection,
      downloadMusicTwo,
      userId,
      Wallet,
      paySong,
      ShoppingCart,
      token,
      addCart,
    };
  },
});
</script>

<style lang="scss" scoped>
@import "@/assets/css/var.scss";
@import "@/assets/css/global.scss";

.content {
  background-color: $color-white;
  border-radius: $border-radius-songlist;
  padding: 10px;
}

.content:deep(.el-table__row.current-row) {
  color: $color-black;
  font-weight: bold;
}

.content:deep(.el-table__row) {
  cursor: pointer;
}

.icon {
  @include icon(1.2em, $color-black);
}
</style>
